//
//  VVComposePictureView.swift
//  Weibo
//
//  Created by 王惠平 on 2017/4/6.
//  Copyright © 2017年 Will Wang. All rights reserved.
//

import UIKit

class VVComposePictureView: UICollectionView {

   
    //图片数据源
    lazy var images:[UIImage] = [UIImage]()
    
    //点击加号完成闭包的回调
    var addPictureClosure: (()->())?
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowlayout = UICollectionViewFlowLayout()
        
        //每项的间距
        let itemMargin: CGFloat = 5
        
        //每个item的宽度和高度
        let itemWidth = (ScreenWidth - 2*itemMargin - 2*HomeCellMargin) / 3
        
        //设置每项的大小
        flowlayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        //垂直间距
        flowlayout.minimumLineSpacing = itemMargin
        
        //水平间距
        flowlayout.minimumInteritemSpacing = itemMargin
        
        super.init(frame: frame, collectionViewLayout: flowlayout)
        
        backgroundColor = UIColor.red
        
        setupUI()
        
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    private func setupUI() {
        
        //默认配图隐藏
        isHidden = true
    
        //注册cell
        register(VVComposePictureViewCell.self, forCellWithReuseIdentifier: ComposePictureViewCellIdentifier)
    
        //设置代理和数据源
        delegate = self
        dataSource = self
    }

    //添加图片
    func addImage(image: UIImage) {
        
        if images.count >= 9 {
            
            return
        }
        
        //显示配图
        isHidden = false
        
        images.append(image)
        
        //重新加载数据
        reloadData()
    }
}

//代理实现
extension VVComposePictureView: UICollectionViewDelegate,UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if images.count == 0 || images.count == 9 {
            
            return images.count
        }
        
        return images.count + 1
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ComposePictureViewCellIdentifier, for: indexPath) as! VVComposePictureViewCell
        
        if indexPath.item == images.count {
            
            //最后一个图片
            cell.image = nil
            
        } else {
            
            //获取对应的图片
            let image = images[indexPath.item]
            
            cell.image = image
            
            cell.indexPath = indexPath
            
            //设置删除的闭包
            cell.deletePicClosure = { [weak self] (index: Int)->() in
                
                //根据索引删除图片
                self?.images.remove(at: index)
                
                //数组没有图片
               if self?.images.count == 0 {
                    
                    //隐藏当前配图
                self?.isHidden = true
                
                }
                
                self?.reloadData()
                
            }
        }
        
        return cell
        
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        //判断点击的是否最后一个cell
        if indexPath.item == images.count {
            
            //最后一张图片
            addPictureClosure?()
        }
    }
    
}

//自定义配图cell
class VVComposePictureViewCell: UICollectionViewCell {
    
    //图片
    fileprivate lazy var imagView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    
    //删除图片按钮
    fileprivate lazy var deleteButton: UIButton = {
       
        let button = UIButton()
        
        //点击事件
        button.addTarget(self, action: #selector(deletePicAction), for: .touchUpInside)
        button.setImage(UIImage(named:"compose_photo_close"), for: .normal)
        
        return button
        
    }()
    
    //记录当前的indexPath
    var indexPath: IndexPath?
    
    //删除图片的闭包
    var deletePicClosure: ((Int)->())?
    
    var image: UIImage? {
        
        didSet {
            
            if image == nil {
                
                //设置加号图片
                imagView.image = UIImage(named: "compose_pic_add")
                
                //隐藏删除按钮
                deleteButton.isHidden = true
                
            } else {
                
                imagView.image = image
                
                //显示删除按钮
                deleteButton.isHidden = false

            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        contentView.addSubview(imagView)
        contentView.addSubview(deleteButton)
        
        imagView.snp.makeConstraints { (make) in
            
            make.edges.equalTo(contentView)
        }
        
        deleteButton.snp.makeConstraints { (make) in
            
            make.top.equalTo(imagView)
            make.trailing.equalTo(imagView)
        }
        
    }
    
    //删除图片
    @objc private func deletePicAction() {
        
        //删除对应的图片
        if let currentIndexPath = indexPath {
            
            //回调删除图片索引
            deletePicClosure?(currentIndexPath.item)
        }
        
    }
}

